package com.qiy.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author qiyang
 * @date 2020年04月17日
 * 学习流控
 */
@RestController
@Slf4j
public class FlowLimitController {

    @GetMapping("/testA")
    public String testA() {
//        try {
//            TimeUnit.MILLISECONDS.sleep(800);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "--------> testA";
    }

    @GetMapping("/testB")
    public String testB() {
        log.info(Thread.currentThread().getName() + "\t" + "testB");
        return "--------> testB";
    }

    @GetMapping("/testD")
    public String testD() {
        try {
            log.info("testD");
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "--------> testD RT";
    }

    @GetMapping("/testE")
    public String testE() {
        log.info("testE 异常比例");
        int age = 10 / 0;
        return "--------> testE 异常比例";
    }

    @RequestMapping("/testHotkey")
    @SentinelResource(value = "testHotkey", blockHandler = "deal_testHotKey")
    public String testHotkey(@RequestParam(value = "param1", required = false)String param1,
                             @RequestParam(value = "param2", required = false)String param2) {
        log.info("输入参数 param1={}, param2={}", param1, param2);
        // 异常不管，只管配置的限流参数
        //int age = 10/0;
        return "测试热点key 正常返回数据";
    }


    public String deal_testHotKey(String param1, String param2, BlockException exception){
        log.info("输入参数 param1={}, param2={}", param1, param2);
        return "当前浏览过大，返回服务降级后的数据";
    }
}